/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: OtcMsgPresenter.java
 *   @Date: 19-1-30 上午11:10
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.otc.presenter;

import android.content.Intent;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.bhex.app.base.AppUI;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BasePresenter;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.response.ResultResponse;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.otc.OtcConstant;
import io.bhex.sdk.otc.OtcMessageApi;
import io.bhex.sdk.otc.OtcOrderApi;
import io.bhex.sdk.otc.bean.OtcMessageResponse;
import io.bhex.sdk.otc.bean.OtcOrderInfoResponse;
import io.bhex.sdk.otc.bean.OtcUploadImgResponse;

public class OtcMsgPresenter extends BasePresenter<OtcMsgPresenter.OtcMsgUI> {
    private String orderId="";
    private Timer timer;
    private TimerTask timerTask;
    private List<OtcMessageResponse.MessageBean> currentMsgList = new ArrayList<>();
    private OtcOrderInfoResponse orderInfo;
    private boolean isHasNewData;

    /**
     * 上传图片
     * @param path
     * @param simpleResponseListener
     */
    public void uploadImage(String path, SimpleResponseListener<OtcUploadImgResponse> simpleResponseListener) {

        OtcMessageApi.uploadImage(path,simpleResponseListener);
    }

    public OtcOrderInfoResponse getOrderInfo() {
        return orderInfo;
    }

    public interface OtcMsgUI extends AppUI{
        void sendMsgSuccess();

        void showMessageList(List<OtcMessageResponse.MessageBean> currentMsgList);

        void showOrderInfo(OtcOrderInfoResponse orderInfo);
    }

    @Override
    public void onUIReady(BaseCoreActivity activity, OtcMsgUI ui) {
        super.onUIReady(activity, ui);
        Intent intent = getActivity().getIntent();
        if (intent != null) {
            orderInfo = (OtcOrderInfoResponse)intent.getSerializableExtra("order");
            getUI().showOrderInfo(orderInfo);
            orderId = orderInfo.getId();
            getMessageList(false,false);
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        startTimer();
    }

    @Override
    public void onPause() {
        super.onPause();
        stopTimer();
    }

    private void startTimer() {
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                getMessageList(true,false);
                getOrderDetail(true,orderId);
            }
        };
        timer.schedule(timerTask,OtcConstant.TIMER_DELAY,OtcConstant.TIMER_PERIOD);

    }

    /**
     * 获取消息列表
     */
    private void getMessageList(final boolean isAutoRefresh, final boolean isLoadMore) {
        if (TextUtils.isEmpty(orderId)) {
            return;
        }
        String startId ="";
//        if (!currentMsgList.isEmpty()) {
//            startId = currentMsgList.get(0).getId();
//        }
        OtcMessageApi.messageList(orderId,startId,1000,new SimpleResponseListener<OtcMessageResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OtcMessageResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,!isAutoRefresh)) {
                    isHasNewData = false;
                    List<OtcMessageResponse.MessageBean> data = response.getArray();
                    if (data != null) {
//                        if (isAutoRefresh) {
//                            currentMsgList.addAll(0,data);
//                        }
//                        if (isLoadMore) {
//                            currentMsgList.addAll(data);
//                        }
                        if (currentMsgList.isEmpty()) {
                            Collections.reverse(data);
                            currentMsgList.addAll(data);
                            isHasNewData = true;
                        }else{
                            OtcMessageResponse.MessageBean messageBean = currentMsgList.get(currentMsgList.size() - 1);
                            long id = Long.valueOf(messageBean.getId());

                            for (int i = data.size() - 1; i >= 0; i--) {
                                OtcMessageResponse.MessageBean newMessageBean = data.get(i);
                                long newId = Long.valueOf(newMessageBean.getId());
                                if (newId>id){
                                    currentMsgList.add(newMessageBean);
                                    isHasNewData = true;
                                }
                            }
                        }

                        if (isHasNewData) {
                            getUI().showMessageList(currentMsgList);
                        }
                    }

                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });

    }

    /**
     * 获取订单详情
     * @param isAutoReq
     * @param orderId
     */
    public void getOrderDetail(final boolean isAutoReq, String orderId) {
        if (!UserInfo.isLogin()) {
            return;
        }
        if (TextUtils.isEmpty(orderId)) {
            return;
        }
        OtcOrderApi.getOrderInfo(orderId,new SimpleResponseListener<OtcOrderInfoResponse>(){

            @Override
            public void onBefore() {
                super.onBefore();
                if (!isAutoReq) {
                    getUI().showProgressDialog("","");
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (!isAutoReq) {
                    getUI().dismissProgressDialog();
                }
            }

            @Override
            public void onSuccess(OtcOrderInfoResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    orderInfo = response;
                    getUI().showOrderInfo(response);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });

    }


    private void stopTimer() {
        if (timerTask!=null){
            timerTask.cancel();
        }
        if (timer != null) {
            timer.cancel();
        }
    }

    /**
     * 发送消息
     * @param msg
     * @param msgType
     */
    public void sendMessage(String msg, int msgType) {
        if (TextUtils.isEmpty(orderId)) {
            return;
        }
        OtcMessageApi.sendMessage(orderId,msg,msgType,new SimpleResponseListener<ResultResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(ResultResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    if (response.isSuccess()) {
                        getUI().sendMsgSuccess();
                        return;
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

}
